package com.CodeCraft.builder;

import com.CodeCraft.bean.Constants;
import com.CodeCraft.bean.FieldInfo;
import com.CodeCraft.bean.TableInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class BuildPo {
    private static final Logger logger = LoggerFactory.getLogger(BuildPo.class);

    public static void execute(TableInfo tableInfo){
        File folder = new File(Constants.PATH_PO);
        if(!folder.exists()){
            folder.mkdirs();
        }

//        File file = new File(folder,tableInfo.getBeanName()+".java");
//        try {
//            file.createNewFile();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }

        File poFile = new File(folder,tableInfo.getBeanName()+".java");

        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;

        try{
            out = new FileOutputStream(poFile);
            outw = new OutputStreamWriter(out,"utf8");
            bw = new BufferedWriter(outw);
            bw.write("package "+Constants.PACKAGE_PO+";");
            bw.newLine();
            bw.newLine();
            bw.write("import java.io.Serializable;");
            bw.newLine();
            if(tableInfo.getHavedate() || tableInfo.getHaveDateTime()){
                bw.write("import java.util.Date;");
                bw.newLine();
            }

            if(tableInfo.getHaveBigDecimal()){
                bw.write("import java.math.BigDecimal;");
                bw.newLine();
            }

            bw.newLine();
            bw.newLine();

            //构建类注释
            BuildComment.createClassComment(bw,tableInfo.getComment());



            bw.write("public class "+tableInfo.getBeanName()+" implements Serializable {");
            bw.newLine();

            for(FieldInfo fieldInfo: tableInfo.getFieldList()){
                bw.write("\tprivate "+ fieldInfo.getJavaType()+" "+ fieldInfo.getPropertyName()+";");
                bw.newLine();
                bw.newLine();
            }

            bw.write("}");
            bw.flush();
        }catch(Exception e){
            logger.error("创建po失败",e);
        }finally{
            if(bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if(outw!=null){
                try {
                    outw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }
        }
        if(out!=null){
            try {
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
